package com.coocaa.launcher;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.KeyEvent;
import android.view.ViewGroup;

import com.coocaa.launcher.framework.launcherhost.LauncherHostView;
import com.coocaa.launcher.framework.launcherhost.LauncherHostView.ILauncherHostViewListener;
import com.coocaa.launcher.framework.launcherhost.LauncherHostViewController;
import com.coocaa.launcher.framework.manager.homekey.HomeKeymanager;
import com.coocaa.launcher.framework.sidebar.ItemContainer;
import com.coocaa.launcher.guide.GuideLayout;
import com.coocaa.launcher.guide.GuideLayout.OnGuideVisibleCallback;
import com.coocaa.launcher.pattern.normal.pick.PickActivity;
import com.coocaa.launcher.sidebar.setting.item.backexit.BackExit;
import com.coocaa.launcher.wallpaper.WallpaperManager;
import com.coocaa.x.app.framework.app.LiteAppApplication;
import com.coocaa.x.framework.data.JObject;
import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.framework.utils.Storage;
import com.coocaa.x.service.XServiceManager;
import com.coocaa.x.service.litecontent.LiteContentServiceConnecter;
import com.coocaa.x.uipackage.ThemeActivity;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.skyworth.logsdk.appstore.LogAPIForAppStore;
import com.tianci.appstore.R;
import com.tianci.appstore.utils.SkyConstants;

import java.io.File;
import java.util.List;

public class EasyLauncherActivity extends LauncherBaseActivity implements ILauncherHostViewListener,
        OnGuideVisibleCallback {
    @Override
    public String getName() {
        // TODO Auto-generated method stub
        return "电视派桌面主页";
    }

    public static EasyLauncherActivity activity = null;
    private static final String META_KEY_DEFAULT_LAUNCHER_CONTROLLER = "default_launcher_controller";
    private LauncherHostView launcher = null;
    private GuideLayout mGuideLayout = null;
    private static boolean pressAgainToExit = false;
    private int doubleBackInterval = 2000; // 两次按“返回”键之间的间隔

    private long log_starttime_st = 0;
    public boolean isSystemSetting = false;
    private final static int MSG_HIDE_LAUNCHER = 0;
    public static final String START_GUIDE_FILE_ABSOLUTEPATH = "/data" + File.separator + "ccos"
            + File.separator + "startGuideFile";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Fresco.initialize(this);
        Storage.addListener(null);
        log_starttime_st = System.currentTimeMillis();
        super.onCreate(savedInstanceState);
        ItemContainer.parseSettingXml(this);
        HomeKeymanager.getInstance().init(this);
        WallpaperManager.getInstance().init(this);
        SkyConstants.initResolution();
        post(new Runnable() {
            @Override
            public void run() {
                if(!LiteAppApplication.getFirstLaunch("FIRST_TVPAI")){
                    try {
                        XServiceManager.getLiteCCConnectorService().firstStartAppPoints("FIRST_TVPAI");
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
                if (LiteAppApplication.isSkyDongle() && isNeedShowBootGuide() && HomeKeymanager.getInstance().getAppStoreIsHomePage()) {
                    try {
                        XServiceManager.getLiteCCConnectorService().startGuide();
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    initMainLayout();
                } else if (LiteAppApplication.isFirstStart() && !LiteAppApplication.isSkyDongle()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mGuideLayout = new GuideLayout(EasyLauncherActivity.this, getMainLooper());
                            mGuideLayout.setGuideVisibleCallback(EasyLauncherActivity.this);
                            if (LiteAppApplication.isMarketChannel()) {
                                mGuideLayout.setImages(new int[]{R.drawable.guide_1, R.drawable.guide_2,
                                        R.drawable.guide_3});
                            } else {
                                mGuideLayout.setImages(new int[]{R.drawable.guide_1, R.drawable.guide_2,
                                        R.drawable.guide_3});
                            }
                            setContentView(mGuideLayout);
                        }
                    });
                    String channel = LiteAppApplication.getDeviceChannel();
                    if (channel.toLowerCase().contains("common")
                            || channel.toLowerCase().contains("market")) {
                        try {
                            XServiceManager.getLiteConfigService().saveBooleanConfig(
                                    BackExit.BACK_EXIT, false);
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    } else {
                        try {
                            XServiceManager.getLiteConfigService().saveBooleanConfig(
                                    BackExit.BACK_EXIT, true);
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }
                }
                else {
                    initMainLayout();
                }
                try {
                    exitSwitch = XServiceManager.getLiteConfigService().getBooleanValue(
                            BackExit.BACK_EXIT, true);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        try {
            if(launcher != null)
                launcher.destroy();
            LiteAppApplication.destroy();
            WallpaperManager.getInstance().destory();
            HomeKeymanager.getInstance().unInit();
            Fresco.shutDown();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        super.onDestroy();
    }

    private boolean isNeedShowBootGuide()
    {
        File startGuideFile = new File(START_GUIDE_FILE_ABSOLUTEPATH);
        if (startGuideFile.exists())
        {
            LogUtils.d("wait","isNeedGuide no:"+startGuideFile.getAbsolutePath());
            return false;
        } else
        {
            LogUtils.d("wait","isNeedGuide");
            return true;
        }
    }

    private LauncherHostViewController getDefaultController() {
        String clazz = (String) Android.getMetaData(this, getPackageName(),
                META_KEY_DEFAULT_LAUNCHER_CONTROLLER);
        if (clazz != null) {
            try {
                Class<?> c = Class.forName(clazz);
                return (LauncherHostViewController) c.newInstance();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }

    private boolean bDoSomething = false;

    @Override
    protected void onNewIntent(Intent intent) {
        bDoSomething = false;
    }

    @Override
    public void onCreate(LauncherHostView hostview) {
        LogAPIForAppStore.desktopStartTime((int) (System.currentTimeMillis() - log_starttime_st));
        bDoSomething = false;
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (launcher != null) {
            LogUtils.d("onPause", "sunny onPause onResume:" + launcher.getAlpha() + isSystemSetting);
            launcher.setAlpha(1f);
        }
        isSystemSetting = false;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (launcher != null) {
            LogUtils.d("onPause", "sunny onPause:" + launcher.getAlpha() + isSystemSetting);
            handler.sendEmptyMessageDelayed(MSG_HIDE_LAUNCHER, 2000);
        }
    }

    Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            if (msg.what == MSG_HIDE_LAUNCHER) {
                LogUtils.d("onPause", "sunny onPause handlersss:" + isSystemSetting + "; " + launcher.getAlpha());
                if (launcher != null && isSystemSetting) {
                    launcher.setAlpha(0);
                }
            }
        }
    };

    @Override
    protected void onStop() {
        super.onStop();

        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        RunningTaskInfo info = manager.getRunningTasks(1).get(0);
        String packageName = info.topActivity.getPackageName(); // 包名
        if (!packageName.equals(getPackageName()))
            bDoSomething = true;
    }

    @Override
    public void onDestroy(LauncherHostView hostview) {
        // TODO Auto-generated method stub
        LauncherHostView.uninit();
    }

    public static boolean exitSwitch = false; // 用来控制是否允许退出桌面

    private static class Current_LauncherData extends JObject {
        public static class Current_LauncherDataRes {
            public static class Current_LauncherDataResItem {
                public String activity, pkgname;
            }

            public List<Current_LauncherDataResItem> resource_items;
            public int total_count;
        }

        public int error_code;
        public String error_msg;
        public Current_LauncherDataRes resource;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        LogUtils.d("key", "EasyLauncherActivity onKeyDown, keycode = " + keyCode);
        if (keyCode != KeyEvent.KEYCODE_BACK && exitSwitch) {
            pressAgainToExit = false;
        }
        if (launcher != null && launcher.onKeyDown(keyCode, event))
            return true;
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            try {
                if (!XServiceManager.getLiteConfigService().getBooleanValue(BackExit.BACK_EXIT,
                        false)) {
                    return true;
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            exitLauncher(true);
            // LogUtils.d("exit", "activity on back key, exitSwitch = " + exitSwitch
            // + ", pressAgain to exit = " + pressAgainToExit);
            // if (exitSwitch)
            // {
            // if (pressAgainToExit)
            // {
            // exitLauncher(false);
            // } else
            // {
            // if (isSystemLauncher())
            // {
            // exitLauncher(true);
            // } else
            // {
            // pressAgainToExit = true;
            // mainHandler.sendEmptyMessageDelayed(0, doubleBackInterval);
            // TipToast.getInstance(this).showToast(
            // SkinManager.getResDrawable(R.drawable.toast_icon_exit),
            // getString(R.string.press_again_to_exit));
            // }
            // }
            //
            // }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exitLauncher(boolean launcher) {
        // CoocaaVersion cv = null;
        // try
        // {
        // cv = CoocaaApplication.getCoocaaVersion();
        // } catch (Exception e)
        // {
        // }
        // if (cv != null && cv.major >= 5)
        // {
        // if (launcher)
        // {
        // bDoSomething = false;
        // try
        // {
        // Intent arg0 = new Intent();
        // arg0.setClassName("com.tianci.tv", "com.tianci.tv.SkyLauncher");
        // startActivity(arg0);
        // } catch (Exception e)
        // {
        // e.printStackTrace();
        // }
        // }
        // }

        if (PickActivity.pickActivity != null)
            PickActivity.pickActivity.finish();
        finish();
    }

    public boolean isSystemLauncher() {
        try {
            String result = LiteContentServiceConnecter.getService().call(
                    "setting://com.coocaa.launcher/current_launcher?action=get");
            Current_LauncherData data = Current_LauncherData.parseJObject(result,
                    Current_LauncherData.class);
            if (data != null && data.error_code == 0 && data.resource.total_count > 0) {
                if (data.resource.resource_items.get(0).pkgname.equals(getPackageName())) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    static class MainHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            pressAgainToExit = false;
            super.handleMessage(msg);
        }
    }

    private void initMainLayout() {
        activity = this;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                LauncherHostView.init(EasyLauncherActivity.this, EasyLauncherActivity.this);
                launcher = LauncherHostView.getInstance();
                if (launcher.getParent() != null) {
                    ViewGroup parent = (ViewGroup) launcher.getParent();
                    parent.removeView(launcher);
                }
                setContentView(launcher);
                launcher.create(getDefaultController());
            }
        });
    }

    @Override
    public void onGuideVisible(boolean visible) {
        // boolean showGuide = XServiceManager.getLiteConfigService()
        // .getBooleanValue("show_guide", true);
        // if (showGuide)
        // copyDefulatDB();
        mGuideLayout.destory();
        initMainLayout();
    }

    // onActivityResult无法使用了，因为此activity的launchMode为singleInstance
    // @Override
    // protected void onActivityResult(int requestCode, int resultCode, Intent data)
    // {
    // // TODO Auto-generated method stub
    // launcher.onActivityResult(requestCode, resultCode, data);
    // }
}